package com.fuzongle.tank.service.impl;

import com.fuzongle.tank.base.BaseService;
import com.fuzongle.tank.base.JsonResult;
import com.fuzongle.tank.dao.MailRecordDao;
import com.fuzongle.tank.entity.MailRecord;
import com.fuzongle.tank.service.MailRecordService;
import com.fuzongle.tank.utils.MailUtil;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.mail.MessagingException;
import javax.mail.internet.AddressException;
import java.io.UnsupportedEncodingException;
import java.util.Date;
import java.util.List;

/**
 * @Auther: fuzongle
 * @Date: 2020/6/2 14:06
 * @Description:邮件记录 业务层实现类
 */
@Service
public class MailRecordServiceImpl extends BaseService implements MailRecordService {

    @Autowired
    private MailRecordDao mailRecordDao;

    @Autowired
    private MailUtil mailUtil;

    /**
     *
     * @param page
     * @param size
     * @param title
     * @return
     */
    @Override
    public JsonResult selectList(Integer page,Integer size,String title) {
        //排序
        PageHelper.startPage(page, size,getOrderBy("send_time","desc"));
        //查询发送过的短信内容
        List<MailRecord> userList = mailRecordDao.selectList(title);
        PageInfo<MailRecord> pageInfo = new PageInfo<>(userList);
        return JsonResult.success(pageInfo.getTotal(),pageInfo.getList());
    }

    @Override
    public MailRecord selectById(Integer id) {
        return mailRecordDao.selectById(id);
    }

    @Override
    public JsonResult insert(MailRecord mailRecord) {

        try {
            //发送邮件
            mailUtil.sendMail(mailRecord.getReceiverMail(), mailRecord.getTitle(), mailRecord.getContent());
        } catch (AddressException e) {
            e.printStackTrace();
        } catch (MessagingException e) {
            e.printStackTrace();
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        mailRecord.setStatus(1);
        mailRecord.setSendTime(new Date());
        mailRecordDao.insert(mailRecord);
        return JsonResult.success();
    }

    @Override
    public JsonResult delete(Integer id) {
        int rows=0;
        rows=mailRecordDao.delete(id);
        if (rows>0){
            return  JsonResult.success();
        }
        return JsonResult.error();
    }
}